package org.iplugin.version.handler;

import org.iplugin.version.model.IModifiedPomVersion;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;

/**
 * 　　* @Description: maven property update
 * 　　* @author shangyouzhi1
 * 　　* @date 2022/11/27 15:02
 */
public class IVersionUpdatePropertyHandler extends IVersionUpdateAbstractHandler {


    @Override
    public void updateVersion(IModifiedPomVersion modifiedPomVersion) {

        Model model = modifiedPomVersion.getModel();
        Properties properties = model.getProperties();
        List<Dependency> dependencies = this.getDependency(model);
        for (Dependency dependency : dependencies) {
            String dependencyVersion = dependency.getVersion();
            String newVersion = newVersionMap.get(dependency.getGroupId() + ":" + dependency.getArtifactId());
            if (StringUtils.isNotBlank(newVersion) && !StringUtils.equals(dependencyVersion, newVersion)) {
                if (StringUtils.startsWith(dependencyVersion, "${")) {
                    String prop = StringUtils.substring(dependencyVersion, 2, dependencyVersion.lastIndexOf("}"));
                    String targetProp = properties.getProperty(prop);
                    this.getLog().info("更新property：" + targetProp+ "更新前：" + dependencyVersion + ",更新后：" + newVersion);
                    properties.setProperty(prop, newVersion);
                    modifiedPomVersion.modifiedVersion();
                }
            }
            if (getNextHandler() != null) {
                getNextHandler().updateVersion(modifiedPomVersion);
            }

        }
    }
}
